#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
#include <memory>
using namespace std;
int main(int argc, char *argv[])
{

    if (argc != 3)
    {
        cerr << "Usage:" << argv[0] << " local-port" << endl;
        exit(0);
    }
    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "client create sockfd error!\n"
             << endl;
    }
    // 客户端一般不用绑定套接字，操作系统会在第一次发送消息时自动绑定本机ip和一个随机的port
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_port = htons(port);
    // 执行向服务端发送数据以及接收服务端响应
    while (true)
    {
        string line;
        cout << "please input: ";
        getline(cin, line);
        ssize_t res = sendto(sockfd, line.c_str(), line.size(), 0, (struct sockaddr *)&server, sizeof(server));

        if (res > 0)
        {
            struct sockaddr_in temp;
            memset(&temp, 0, sizeof(temp));
            char buff[1024];
            socklen_t len = 0;
            int n = recvfrom(sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&temp, &len);
            if (n > 0)
            {
                buff[n] = '\0';
                cout << buff << endl;
            }
            else
            {
                cerr << "client recvfrom error" << endl;
                break;
            }
        }
        else
        {
            cout << "client sendto error" << endl;
            break;
        }
    }
    return 0;
}